const card = document.getElementById('card')
const channel = new BroadcastChannel('card-channel')
channel.onmessage = (e) => {
  const clientCoordinates = screen2client(...e.data)
  card.style.left = clientCoordinates[0] + 'px'
  card.style.top = clientCoordinates[1] + 'px'
}

const init = () => {
  const url = new URL(location.href)
  const imgName = url.searchParams.get('name') || 'vue'
  // 拼接 img src
  card.src = `./${imgName}.png`
}


// 拖动实现
card.onmousedown = e => {
  let x = e.pageX - card.offsetLeft
  let y = e.pageY - card.offsetTop
  window.onmousemove = (e) => { // 跟随鼠标移动
    const cx = e.pageX - x
    const cy = e.pageY - y

    card.style.left = cx + 'px'
    card.style.top = cy + 'px'
    
    const screenCoordinates = client2screen(cx, cy)
    channel.postMessage(screenCoordinates)

  }
  window.onmouseup = () => {
    window.onmousemove = null
    window.onmouseup = null
  }
}

// 辅助函数
// 浏览器标签页工具栏高度 (除视口区域的高度)
const barHeight = () => {
  return window.outerHeight - window.innerHeight
}
// 屏幕坐标 to 视口坐标
const client2screen = (x, y) => {
  const screenX = x + window.screenX
  const screenY = y + window.screenY + barHeight()
  return [screenX, screenY]
}
// 视口坐标 to 屏幕坐标
const screen2client = (x, y) => {
  const screenX = x - window.screenX
  const screenY = y - window.screenY - barHeight()
  return [screenX, screenY]
} 

init()